import request from '../../../utils/request.js'
import countDown from '../../../utils/countDown.js'
import * as validator from '../../../utils/validator.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttonText: '获取',
    buttonDisabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    countDown.end()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '智能急救培训',
      path: '/pages/startup/startup'
    }
  },

  bindInput(e) {
    this.mobile = e.detail.value
  },

  bindGetCode(e) {
    if (!validator.isMobile(this.mobile)) {
      this.showError('请输入正确手机号')
      return false;
    }
    this.lockedMobile = this.mobile // 锁定当前手机号
    request.post('/api/common/v1/sms', {
      appKey: '',
      mobile: this.mobile,
      smsType: 2
    }).then(res => {
      this.countDownStart()
    })
  },

  countDownStart() {
    this.setData({
      buttonText: 60,
      buttonDisabled: true
    })
    countDown.start(60, val => {
      if (val == 0) {
        this.setData({
          buttonDisabled: false,
          buttonText: '获取'
        })
      } else {
        this.setData({
          buttonText: val
        })
      }
    })
  },

  bindSubmit(e) {
    if (!validator.isMobile(e.detail.value.mobile)) {
      this.showError('请输入正确手机号')
      return false;
    }
    if (!this.lockedMobile) {
      this.showError('请获取验证码')
      return false;
    }
    if (!(e.detail.value.code)) {
      this.showError('请输入手机验证码')
      return false;
    }
    if (e.detail.value.mobile != this.lockedMobile) {
      this.showError('手机号变更请重新获取验证码')
      return false;
    }
    if (!validator.isPassword(e.detail.value.password)) {
      this.showError('请填写6到20位密码，不能包含空白字符')
      return false;
    }

    wx.showLoading({
      title: '正在重置密码...',
    })
    request.post('/api/weChatMini/v1/user/forgetPassword', {
      mobile: e.detail.value.mobile,
      password: e.detail.value.password,
      verificationCode: e.detail.value.code,
    }).then(res => {
      wx.hideLoading()
      wx.navigateBack()
    }).then(err => {
      wx.hideLoading()
    })
  },

  showError(str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  }
})